const database = require("../../database/index");
const jwt = require("jsonwebtoken");

const config = require("../config");
const dayjs = require("dayjs");
// 管理员登录
exports.login = (req, res) => {
    const userinfo = req.body;
    if (!userinfo.username) {
        return res.response("用户名不能为空");
    };
    if (!userinfo.password) {
        return res.response("密码不能为空");
    };
    const sql = `select * from admin where username=?`;
    database.query(sql, userinfo.username, function (err, results) {
        if (err) return res.response(err);
        if (results.length !== 1) return res.response("管理员不存在");
        const compareResult = userinfo.password === results[0].password;
        if (!compareResult) {
            return res.response("密码错误");
        };
        const { id, username } = results[0];
        let user = {
            id,
            username,
        };
        const token = jwt.sign(user, config.jwtSecretKey, {
            expiresIn: config.expiresIn,
        });
        res.send({
            code: 0,
            message: "登录成功！",
            result: {
                token: "Bearer " + token,
                userInfo: results[0],
            },
        });
    });
};
// 修改
exports.edit = (req, res) => {
    const { id } = req.body;
    let sql = "update admin set ? where id=?";
    const updated = dayjs().format("YYYY-MM-DD HH:mm:ss");
    database.query(sql, [{ ...req.body, updated }, id], (err) => {
        if (err) return res.response(err);
        res.response("修改成功", 0);
    });
};


